#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#define _size 1024
using namespace std;

string GetOtherMessage()
{
    static int cnt = 1;
    string messageid = to_string(cnt);
    cnt++;
    pid_t pid = getpid();
    string messagepid = to_string(pid);

    string message = "massageid: ";
    message += messageid;
    message += "massagepid: ";
    message += messagepid;
    return message;
}

void SubProcessWrite(int wfd)
{ // 子进程写入端
    int pipesize = 0;
    string message = "father, i am your son";
    char c = 'A';
    while (true)
    {
        cerr << "+++++++++++++++++++++++++" << endl;
        string info = message + GetOtherMessage();
        write(wfd, info.c_str(), info.size());
        cerr << info << endl;
        sleep(1);
        // write(wfd,&c,1);
    }
}
void FatherProcessRead(int rfd)
{ // 父进程读入端
    char inbuff[_size];
    while (true)
    {
        cout << "-------------------------" << endl;
        ssize_t n = read(rfd, inbuff, sizeof(inbuff) - 1);
        if (n > 0)
        {
            inbuff[n] = '\0';
            cout << "getmessage: " << inbuff << endl;
        }
        else if (n == 0)
        { // 如果read的返回值为0，表示写入端关闭，我们读到了文件的末尾
            cout << "写入端关闭，父进程放弃读数据" << endl;
        }
        else
        {
            cerr << "read error" << endl;
        }
    }
}

int main()
{
    // 1.创建管道
    int pipefd[2]; // 输出型参数，用来获得rfd、wfd.
    int n = pipe(pipefd);
    if (n != 0)
    {
        cerr << "errno: " << errno << ":"
             << "errstring:" << strerror(errno) << endl;
        return 1;
    }
    cout << "pipefd[0]: " << pipefd[0] << " pipefd[1]: " << pipefd[1] << endl;
    sleep(1);

    // 创建子进程,子进程发送数据，父进程读取数据
    pid_t id = fork();
    if (id < 0)
        cout << "fork" << endl;
    if (id == 0)
    {
        // child
        cout << "子进程关闭不需要的fd了，准备发消息了" << endl;
        close(pipefd[0]); // 子进程关闭读端
        // 发送消息
        SubProcessWrite(pipefd[1]);
        close(pipefd[0]); // 发送结束，关闭写端
        exit(0);
    }
    cout << "父进程关闭不需要的fd了，准备接收消息了" << endl;
    sleep(1);
    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);
    close(pipefd[0]);
    return 0;
}